package com.cavy.platform.server.domain.job;

import com.cavy.platform.server.domain.SchedulingStrategy;
import com.cavy.platform.server.domain.Stage;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.cavy.platform.server.domain.job.JobStatus.ERROR;
import static com.cavy.platform.server.domain.job.JobStatus.FINISH;

/**
 * @author 唐旭
 * @Date 2018/7/20
 * 任务生成后就不可变
 */
@Slf4j
@Data
@Accessors(chain = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "className", defaultImpl = Job.class)
@JsonSubTypes({
        @JsonSubTypes.Type(value = GitRemoteJob.class, name = "GitRemoteJob"),
        @JsonSubTypes.Type(value = Job.class, name = "Job")})
public class Job {
    protected String number = JobNumberBuilder.build();
    protected String pipelineName;
    protected String projectName;
    protected String workspaceName;
    protected List<JobStage> jobStageList = new ArrayList<>();
    protected SchedulingStrategy schedulingStrategy = SchedulingStrategy.RANDOM;
    protected Date createTime = new Date();
    protected JobStatus status = JobStatus.PENDING;
    protected Date runningTimeOut;

    public void addAllStage(List<Stage> stageList) {
        for (Stage stage : stageList) {
            jobStageList.add(new JobStage(stage));
        }
    }

    public boolean isEnd() {
        return status.equals(ERROR) || status.equals(FINISH);
    }

//    public void stop() {
//        Objects.requireNonNull(BeansProvider.getBean(JobRepository.class)).save(new EndJob(this));
//    }
    //下发任务-记录任务下发目标agent
    //根据调度策略找到目标agent(可用的)
    //使用websocket发送消息到agent
    //监听agent回复,并根据回复修改job状态
    //系统启动后,将之前未完成的任务都设置为[终止]状态
}
